<template>
  <div class="page-find-store">
    <div class="baseDiv">
      <el-form :model="addForm" :rules="rules" ref="addForm" class="addForm">
        <el-form-item label="货主企业" prop="ownerName">
          <search-select style="width: 420px" :disabledSelect="disableSelect" :inputValue="addForm.ownerName" v-model="addForm.ownerName" :params="searchparams"
                         :url="'/maliwms/company/getCompanySelectList'" labelKey="companyName" valueKey="id"
                         :queryParam="queryParam" queryKey="companyName" @changeSelect="handleSelect"></search-select>
        </el-form-item>
        <el-form-item class="el-form-item-right" label="联系人姓名" prop="contactName">
          <el-input style="width: 420px" maxlength="50" placeholder="输入联系人姓名" v-model="addForm.contactName" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model="addForm.contactPhone" placeholder="输入联系人电话" clearable></el-input>
        </el-form-item>
        <el-form-item class="el-form-item-right" label="预计入库时间" prop="instoreTime">
          <el-date-picker type="date" placeholder="选择预计入库时间" v-model="addForm.instoreTime" value-format="yyyy-MM-dd"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="期望存储天数" prop="instoreDays">
          <el-input v-model="addForm.instoreDays" maxlength="4" @keyup.native="verifyInteger(addForm, 'instoreDays')"
                    placeholder="输入期望存储天数" clearable></el-input>
        </el-form-item>
        <el-form-item class="el-form-item-right" label="期望存储地区">
          <div class= "expect-area">
            <el-select style="width: 160px" v-model="expectProv" value-key="id" clearable
                       placeholder="请选择省份"
                       @change="handleProvinceChange">
              <el-option
                v-for="item in provinces"
                :key="item.id"
                :label="item.nodeName"
                :value="item">
                <span style="float: left">{{ item.nodeName }}</span>
              </el-option>
            </el-select>
            <span style="margin-left: 5px; margin-right: 5px; width: 10px; color: #e5e5e5">-</span>
            <el-select style="width: 240px" v-model="expectCities" value-key="id" clearable multiple collapse-tags
                        placeholder="请选择城市" @change="handleCityChange">
              <el-option
                v-for="item in cities"
                :key="item.id"
                :label="item.nodeName"
                :value="item">
                <span style="float: left">{{ item.nodeName }}</span>
              </el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="goods-title">货物信息</div>
    <!--    <egrid class="egrid-class" border
               :data="goodsList"
               :columns="goodsColumns"
               :columns-schema="columnsSchema"
               :columns-props="columnsProps">
        </egrid>-->
    <el-table class="find-store-table" border :header-cell-style="getHeaderCellClass" :data="goodsList" style="width: 100%">
      <el-table-column prop="goodsName" label="货物名称" style="width:6vw;">
        <template slot-scope="scope">
          <el-input size="mini" maxlength="50" v-model="scope.row.goodsName"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="planCount" label="计划入库数量" style="width:12vw;">
        <template slot-scope="scope">
          <el-input maxlength="8" @keyup.native="verifyInteger(scope.row, 'planCount')" size="mini"
                    v-model="scope.row.planCount"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="planWeight" label="计划入库重量(kg)" style="width:12vw;">
        <template slot-scope="scope">
          <el-input maxlength="10" @keyup.native="verifyDecimal(scope.row, 'planWeight')" @blur="convertToNumber(scope.row, 'planWeight')" size="mini"
                    v-model="scope.row.planWeight"></el-input>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.$index == 0" @click.native.prevent="addRow(goodsList)" type="text"
                     class="icon maliiconfont maliicon-img_details_add icon_right"
                     size="small">
          </el-button>
          <el-button v-else @click.native.prevent="deleteRow(scope.$index, goodsList)" type="text"
                     class="icon maliiconfont maliicon-img_details_subtract icon_right"
                     size="small">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="goods-title">入库仓库
      <el-button style="margin-left: 5px" type="primary" plain @click="selectStore">选择仓库</el-button>
    </div>
    <el-table class="find-store-table" border :header-cell-style="getHeaderCellClass" :data="storageList" style="width: 100%">
      <el-table-column prop="storageName" label="仓库名称" show-overflow-tooltip style="width:6vw;">
      </el-table-column>
      <el-table-column prop="storageAddress" label="仓库地址" show-overflow-tooltip style="width:6vw;">
      </el-table-column>
      <el-table-column prop="applicantContact" label="联系人姓名" style="width:12vw;">
        <template slot-scope="scope">
          <el-input size="mini" maxlength="50" v-model="scope.row.applicantContact"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="applicantConTel" label="联系人电话" style="width:12vw;">
        <template slot-scope="scope">
          <el-input type="tel" maxlength="12" size="mini" v-model="scope.row.applicantConTel"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      <input-com :headTitle="'备注(选填)'" :inputValue="addForm.remark" @getInputVal="getInputVal" :headSonTitle="'填写备注'"></input-com>
      <el-row class="btnFrameClass">
        <el-button v-permission="['wms:stockmanager:order:findstore:save']" class="singleBtnClass"
                   type="primary" plain @click="saveData('addForm')">保存</el-button>
        <el-button v-permission="['wms:stockmanager:order:findstore:submit']" class="singleBtnClass"
                   type="primary" @click="submitForm('addForm')">提交</el-button>
      </el-row>
    </div>
    <pc-dialog :is-show="isShowSelectDialog" title="选择仓库" @on-close="isShowSelectDialog = false">
      <store-select :params="params" @selected="selectStorage"></store-select>
    </pc-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import PcDialog from 'components/dialog';
  import inputCom from 'components/input/baseTitleInput.vue';
  import searchSelect from 'components/search-select/searchSelect';
  import StoreSelect from '@/views/wms/storemanage/storeSelect';
  import maValidate from 'utils/common-method/validate/index';
  import {validateTips} from 'utils/tips';
  export default {
    components: {
      inputCom,
      searchSelect,
      PcDialog,
      StoreSelect
    },
    props: {
      roleType: {
        type: Number
      },
      id: [String, Number]
    },
    data() {
      return {
        params: {
          provinceId: null,
          provinceName: null,
          cityIds: null,
          city: []
        },
        orderId: this.id,
        goodsList: [{
          goodsName: '', planCount: '', planWeight: ''
        }],
        goodsColumns: [
          {
            label: '货物名称',
            property: 'goodsName'
          },
          {
            label: '计划入库数量',
            property: 'planCount'
          },
          {
            label: '计划入库重量（kg）',
            property: 'planWeight'
          }
        ],
        storageList: [{
          storageId: null, storageName: '', storageAddress: '', applicantContact: '', applicantConTel: ''
        }],
        businessType: this.id ? 2 : 1, // 操作类型，如：1.找库 2.处理订单
        addForm: {
          id: this.$props.id,
          businessType: this.id ? 2 : 1,
          ownerId: null,
          ownerName: '',
          contactName: '',
          contactPhone: '',
          instoreTime: '',
          instoreDays: '',
          province: '',
          provinceId: null,
          city: [],
          cityIds: [],
          goodsDetailDtoList: [{
            goodsName: '', planCount: '', planWeight: ''
          }],
          storageContact: '',
          storageContactPhone: '',
          storageId: null,
          storageName: '',
          storageAddress: '',
          remark: '',
          operateType: 1
        },
        rules: {
          ownerName: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'}
          ],
          contactName: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'}
          ],
          instoreDays: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'},
            {validator: maValidate.checkNum, trigger: 'blur'}
          ],
          contactPhone: [
            {required: true, validator: maValidate.checkContactNumber, trigger: 'blur'}
          ],
          instoreTime: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'}
          ]
        },
        searchparams: [
          {
            title: '公司名称',
            key: 'companyName',
            style: 'float: left; width: 30rem; color: #8492a6; font-size: 13px'
          },
          {
            title: '联系人',
            key: 'contactName',
            style: 'float: left; width: 15rem; color: #8492a6; font-size: 13px'
          },
          {
            title: '联系人电话',
            key: 'contactPhone',
            style: 'float: left; width: 10rem; color: #8492a6; font-size: 13px; text-align: right'
          }
        ],
        queryParam: { // 搜索数据参数
          companyName: ''
        },
        provinces: [],
        cities: [],
        expectProv: '',
        expectCities: [],
        text: 'text',
        isShowSelectDialog: false // 控制选择仓库弹框是否显示
      };
    },
    created() {
      // 初始化城市数据
      this.initAddressData();
    },
    computed: {
      disableSelect() {
//        console.log('id' + this.id + 'disableSelect: ' + (this.id && this.id !== null));
        return (this.id && this.id !== null);
      }
    },
    mounted() {
      // 判断是否是处理订单页面，如果是则加载订单数据
      if (this.orderId) {
        this.initData();
      }
    },

    methods: {
      // 初始化城市数据
      initAddressData() {
        let address = this.$pcLockr.get(this.$pcEnum.ADDRESS.DISTRICT); // 从浏览器中读取缓存的城市数据
        // 判断有没有缓存的城市数据， 如果有直接用， 如果没有则请求接口
        if (address) {
          this.provinces = address;
          // 去除掉多余三级城市的数据
          this.removeExcrescentData();
          return;
        }
        this.ajax({
          url: '/mdc/address/get4City',
          success: (res) => {
            let data = res.result;
//            console.log(data);
            if (!data) {
              return;
            }
            this.provinces = data;
            // 去除掉多余三级城市的数据
            this.removeExcrescentData();
            // 缓存在浏览器中
            this.$pcLockr.set(this.$pcEnum.ADDRESS.DISTRICT, data);
          }
        });
      },
      // 根据找库订单ID获取找库订单的详细数据
      initData() {
        this.ajax({
          type: 'GET',
          url: '/maliwms/instoreOrder/getOrder/' + this.orderId,
          loading: true,
          success: (res) => {
            setTimeout(() => {
              this.$pcNProgress.done();
            }, 300);
            this.addForm = res.result;
            this.goodsList = this.addForm.goodsDetails ? this.addForm.goodsDetails : [{goodsName: '', planCount: null, planWeight: null}];
            this.cities = this.getCities(res.result.provinceId);
            this.expectProv = this.getSelectOption(res.result.provinceId, this.provinces);
            this.expectCities = res.result.cityIds ? this.getSelectOptionArray(res.result.cityIds, this.cities) : [];
            this.params.provinceId = res.result.provinceId;
            this.params.provinceName = this.expectProv;
            this.params.cityIds = res.result.cityIds;
            this.params.city = this.expectCities;
            this.storageList[0].applicantContact = res.result.storageContact;
            this.storageList[0].applicantConTel = res.result.storageContactPhone;
            this.storageList[0].id = res.result.storageId;
            this.storageList[0].storageName = res.result.storageName;
            this.storageList[0].storageAddress = res.result.storageAddress;
          }
        });
      },
      // 搜索下拉选择货主企业回调函数
      handleSelect(data) {
        if (data) {
          this.addForm.ownerId = data.id;
          this.addForm.ownerName = data.companyName;
          this.addForm.contactName = data.contactName;
          this.addForm.contactPhone = data.contactPhone;
        } else {
          this.addForm.ownerId = null;
          this.addForm.ownerName = null;
          this.addForm.contactName = null;
          this.addForm.contactPhone = null;
        }
      },
      removeExcrescentData() {
        // 去除掉多余三级城市的数据
        this.provinces.forEach(function (province, index) {
          if (province.children) {
            province.children.forEach(function (child, index) {
              if (child.children) {
                child.children = null;
              }
            });
          }
        });
      },
      // 根据服务端返回的省市ID获取下一级城市数据
      getSelectOption(id, optionArray) {
        let option = null;
        optionArray.forEach(function (item, index) {
          if (item.id === id) {
            option = item;
          }
        });
        return option;
      },
      // 根据服务端返回的省市ID获取下一级城市数据
      getSelectOptionArray(ids, optionArray) {
        let option = [];
        optionArray.forEach(function (item, index) {
          ids.forEach((id) => {
            if (item.id === id) {
              option.push(item);
            }
          });
        });
        return option;
      },
      // 根据服务端返回的省市ID获取下一级城市数据
      getCities(provinceId) {
        let cities = [];
        this.provinces.forEach(function (item, index) {
          if (item.id === provinceId) {
            cities = item.children;
          }
        });
        return cities;
      },
      // 备注
      getInputVal(val) {
        this.addForm.remark = val;
      },
      // 删除一行货物数据
      deleteRow(index, rows) {
        rows.splice(index, 1);
      },
      // 添加一行货物数据
      addRow(tableData, event) {
        tableData.push({
          goodsName: '', planCount: '', planWeight: ''
        });
      },
      // 选择省份变化是回调函数
      handleProvinceChange(val) {
//        console.log('handleProvinceChange: ' + JSON.stringify(val));
        this.cities = val.children;
        this.expectCities = [];
        this.addForm.provinceId = val.id;
        this.addForm.province = val.nodeName;
        this.params.provinceId = val.id;
        this.params.provinceName = val;
      },
      // 选择城市变化是回调函数
      handleCityChange(val) {
//        console.log('handleCityChange: ' + JSON.stringify(val));
        this.addForm.cityIds = [];
        this.addForm.city = [];
        let that = this;
        // 循环取出选择的城市数据，获取城市的id和名字
        val.forEach(function (city, index) {
          if (city) {
            that.addForm.cityIds.push(city.id);
            that.addForm.city.push(city.nodeName);
          }
        });
        // 判断选择的城市数组是否empty，如果是则设置为null
        if (this.addForm.cityIds.length === 0) {
          this.addForm.cityIds = null;
          this.addForm.city = null;
        }
        this.params.cityIds = this.addForm.cityIds;
        this.params.city = this.expectCities;
      },
      // 提交找库数据函数
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submitData(true, '/maliwms/instoreOrder/submit');
//            alert('submit!');
          } else {
            return false;
          }
        });
      },
      // 保存找库数据函数
      saveData(formName) {
        // 校验货物企业是否为空
        if (maValidate.stringIsNullOrEmpty(this.addForm.ownerId) && maValidate.stringIsNullOrEmpty(this.addForm.ownerName)) {
          this.errorTip(validateTips.OWNER_NOT_EMPTY);
          return;
        }
        this.submitData(false, '/maliwms/instoreOrder/save');
      },
      // 校验货物数据完整性和仓库数据完整性，并提交数据到后端
      /*
       * 校验货物数据完整性和仓库数据完整性，并提交数据到后端
       * @param val 是否校验货物和仓库必须有数据
       */
      submitData(val, url) {
        this.addForm.businessType = this.businessType;
        this.addForm.id = this.id;
        this.addForm.goodsDetailDtoList = [].concat(this.goodsList);
        let len = this.goodsList.length;
        let pass = true;
        for (let i = 0; i < len; i++) {
          let goods = this.goodsList[i];
          if (maValidate.stringIsNullOrEmpty(goods.goodsName) &&
            maValidate.stringIsNullOrEmpty(goods.planCount) && maValidate.stringIsNullOrEmpty(goods.planWeight)) {
            this.addForm.goodsDetailDtoList.splice(i, 1);
            continue;
          }
          if (maValidate.stringIsNullOrEmpty(goods.goodsName)) {
            pass = false;
//            this.message('请填写货物', 'error', true);
            this.errorTip(validateTips.FILL_GOODS_DATA);
            break;
          }
          if (maValidate.stringIsNullOrEmpty(goods.planCount) || goods.planCount === 0) {
            pass = false;
//            this.message('请填写货物数量', 'error', true);
            this.errorTip(validateTips.FILL_GOODS_DATA);
            break;
          }
          if (maValidate.stringIsNullOrEmpty(goods.planWeight) || goods.planWeight === 0) {
            pass = false;
//            this.message('请填写货物重量', 'error', true);
            this.errorTip(validateTips.FILL_GOODS_DATA);
            break;
          }
        }
        if (val && this.addForm.goodsDetailDtoList.length <= 0) { // 判断货物列表数据是否是empty
          pass = false;
//          this.addForm.goodsDetailDtoList.push({goodsName: '', planCount: '', planWeight: ''});
          this.errorTip(validateTips.FILL_GOODS_DATA);
        }
//        if (!val && this.addForm.goodsDetailDtoList.length <= 0) {
//          this.addForm.goodsDetailDtoList.push({goodsName: '', planCount: '', planWeight: ''});
//        }
        if (!pass) {
          return;
        }
        if (val && !this.storageList[0].id) {
          pass = false;
//          this.message('请选择仓库', 'error', true);
          this.errorTip(validateTips.FILL_STORAGE_INFO);
          return;
        }
        if (this.storageList[0].id && maValidate.stringIsNullOrEmpty(this.storageList[0].applicantContact)) {
          pass = false;
//          this.message('请填写仓库联系人', 'error', true);
          this.errorTip(validateTips.FILL_STORAGE_INFO);
          return;
        }
        if (this.storageList[0].id && maValidate.stringIsNullOrEmpty(this.storageList[0].applicantConTel)) {
          pass = false;
//          this.message('请填写仓库联系人电话', 'error', true);
          this.errorTip(validateTips.FILL_STORAGE_INFO);
          return;
        }
        if (this.storageList[0].id &&
          !maValidate.checkContactNumber({message: validateTips.FILL_RIGHT_STORAGE_CONTACT_PHONE}, this.storageList[0].applicantConTel, this.errorTip)) {
          pass = false;
//          this.message('请填写仓库联系人电话', 'error', true);
//          this.errorTip(validateTips.FILL_STORAGE_CONTACT_PHONE);
          return;
        }
        this.addForm.instoreDays = parseInt(this.addForm.instoreDays);
        this.addForm.storageId = this.storageList[0].id;
        this.addForm.storageName = this.storageList[0].storageName;
        this.addForm.storageAddress = this.storageList[0].storageAddress;
        this.addForm.storageContact = this.storageList[0].applicantContact;
        this.addForm.storageContactPhone = this.storageList[0].applicantConTel;
        // 调用接口提交数据给服务端
        this.ajax({
          url: url,
          data: this.addForm,
          loading: true,
          success: (res) => {
            setTimeout(() => {
              this.$pcNProgress.done();
            }, 300);
            console.log('submit data res: ' + JSON.stringify(res));
            if (res.code === 200) {
              this.successTip(res.message);
              this.$emit('refreshData');
            } else {
              this.errorTip(res.message);
            }
          }
        });
        /* this.$http({
          method: 'POST',
          url: url,
          data: this.addForm
        }).then((res) => {
          if (res.code === 200) {
            this.$emit('refreshData');
          } else {
          }
        }); */
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 校验整数
      verifyInteger(val, prop) {
        maValidate.verifyInteger(val, prop);
      },
      // 校验小数
      verifyDecimal(val, prop) {
        maValidate.verifyDecimal(val, prop);
      },
      emitChange(val) {

      },
      // 控制显示选择仓库页面
      selectStore() {
//        this.loadPage('StoreSelect', {provinceId: this.addForm.provinceId, cityIds: this.addForm.cityIds});
        this.isShowSelectDialog = true;
      },
      selectStorage(data) {
        console.log('data: ' + JSON.stringify(data));
        this.isShowSelectDialog = false;
        this.storageList = data;
      },
      // 定义表头的样式
      getHeaderCellClass({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return 'background: #ffffff; height: 50px; text-align: center !important;';
        } else {
          return '';
        }
      },
      convertToNumber(row, prop) {
        row[prop] = maValidate.convertToNumber(row[prop]);
      }
    }
  };
</script>
<style >
  .page-find-store {
    background-color: #f5f6f7;
    width: 958px;
  }
  .page-find-store .baseDiv {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    height: auto;
    border: 1px solid #e5e5e5;
    background-color: white
  }

  .page-find-store .baseDiv .el-form-item {
    display: inline-block;
    width: 420px;
    margin-left: 20px;
    margin-right: 20px;
  }
  .page-find-store .baseDiv .el-form-item-right {
    float: right;
  }
  .page-find-store .baseDiv .el-form-item .expect-area {
    width: 100%;
    display: flex;
    flex-wrap: wrap
  }
  .page-find-store .find-store-table .cell {
    text-align: center !important;
    color: #333333 !important;
  }

  .page-find-store .find-store-table .el-input__inner {
    text-align: center !important;
  }
  .page-find-store .goods-title {
    padding-left: 20px;
    height: 50px;
    line-height: 50px;
    width: 100%;
    margin-top: 20px;
    border-left: 1px solid #e5e5e5;
    border-right: 1px solid #e5e5e5;
    border-top: 1px solid #e5e5e5;
    background: white
  }

  .page-find-store .addForm {
    width: 100%;
    margin-top: 24px;
  }

  .el-form-item .el-form-item__error {
    /*padding-top: 36px;*/
    /*margin-left: -60px;*/
  }

  .page-find-store .btnFrameClass {
    margin-top: 40px;
    margin-bottom: 20px;
    text-align: center;
  }

  .page-find-store .singleBtnClass {
    width: 140px;
    height: 40px;
  }
  .page-find-store .maliiconfont {
    color: #808080;
  }
</style>

